package com.putao.album.child;

import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.putao.album.R;
import com.putao.album.base.BaseActivity;
import com.putao.album.child.bean.FamilyItem;
import com.putao.album.child.bean.RelationItem;
import com.putao.album.dialog.ConfirmDialogBuilder;
import com.putao.album.util.BitmapHelper;
import com.putao.album.util.CommonUtils;
import com.putao.album.util.HttpRequestUtil;
import com.putao.album.util.Loger;
import com.putao.album.util.PuTaoConstants;
import com.putao.album.util.StringHelper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by chen on 15-6-12.
 */
public class ActivityFamily extends BaseActivity {
    private ActivityFamilyAdapter mAdapter;
    private GridView mGridView;
    String admin_uid;

    private ArrayList<FamilyItem> mDatalist = new ArrayList<FamilyItem>();

    @Override
    public int doGetContentViewId() {
        return R.layout.activity_family;
    }

    @Override
    public void doInitSubViews(View view) {
        queryViewById(R.id.back_btn, true);
        TextView title_tv = (TextView) findViewById(R.id.title_tv);
        title_tv.setText("家人们");
        findViewById(R.id.right_btn).setVisibility(View.INVISIBLE);

        mGridView = (GridView) findViewById(R.id.grid_view);
        mGridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                FamilyItem item = mDatalist.get(position);
                showConfigCancelDialog(item);
                return true;
            }
        });

    }

    @Override
    public void doInitData() {
        doGetData();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_btn:
                finish();
                break;
            default:
                break;
        }
    }

    private void showConfigCancelDialog(final FamilyItem item) {
        if (!CommonUtils.getUsrId().equals(admin_uid)) {
            return;
        }

        if (item.isAdmin()) {
            return;
        }

        new ConfirmDialogBuilder(mContext)
                .setMessage("取消TA对\""+CommonUtils.getBabyName()+"\"的关注后,\n" +
                        "TA将不能看到\""+CommonUtils.getBabyName()+"\"的照片")
                .setPositiveButton("不了", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                .setNegativeButton(getString(R.string.btn_ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        SuperManagerCancelConnect(item);
                    }
                })
                .Create()
                .show();

    }

    private void updateMotherView(FamilyItem mother) {
        boolean isConnected = false;
        if (mother == null) {
            mother = new FamilyItem();
            mother.setTag(RelationItem.Tag.MATHER);
            mother.setName("妈妈");
        } else {
            isConnected = true;
        }

        ImageView mother_icon, mother_unconnected, mother_new;
        TextView mother_name;

        mother_icon = (ImageView) findViewById(R.id.mother_icon);
        mother_unconnected = (ImageView) findViewById(R.id.mother_unconnected);
        mother_new = (ImageView) findViewById(R.id.mother_new);
        mother_name = (TextView) findViewById(R.id.mother_name);

        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(RelationItem.Tag.getResIdByTag(mother.getTag()))
                .showImageOnLoading(BitmapHelper.getLoadingDrawable()).showImageOnFail(BitmapHelper.getLoadingDrawable())
                .bitmapConfig(Bitmap.Config.RGB_565)
                .considerExifParams(true)
                .build();
        ImageLoader.getInstance().displayImage(mother.getAvatar(), mother_icon, options);
        if (isConnected) {
            mother_unconnected.setVisibility(View.INVISIBLE);
        } else {
            mother_unconnected.setVisibility(View.VISIBLE);
        }
        if (mother.isNew()) {
            mother_new.setVisibility(View.VISIBLE);
        } else {
            mother_new.setVisibility(View.INVISIBLE);
        }

        mother_name.setText(mother.getName());

        final FamilyItem finalMother = mother;
        final boolean finalIsConnected = isConnected;
        mother_icon.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (finalIsConnected) {
                    showConfigCancelDialog(finalMother);
                }
                return true;
            }
        });

    }

    private void updateFatherView(FamilyItem father) {
        boolean isConnected = false;
        if (father == null) {
            father = new FamilyItem();
            father.setTag(RelationItem.Tag.FATHER);
            father.setName("爸爸");
        } else {
            isConnected = true;
        }

        ImageView father_icon, father_unconnected, father_new;
        TextView father_name;

        father_icon = (ImageView) findViewById(R.id.father_icon);
        father_unconnected = (ImageView) findViewById(R.id.father_unconnected);
        father_new = (ImageView) findViewById(R.id.father_new);
        father_name = (TextView) findViewById(R.id.father_name);

        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(RelationItem.Tag.getResIdByTag(father.getTag()))
                .showImageOnLoading(BitmapHelper.getLoadingDrawable()).showImageOnFail(BitmapHelper.getLoadingDrawable())
                .bitmapConfig(Bitmap.Config.RGB_565)
                .considerExifParams(true)
                .build();
        ImageLoader.getInstance().displayImage(father.getAvatar(), father_icon, options);

        if (!isConnected) {
            father_unconnected.setVisibility(View.VISIBLE);
        } else {
            father_unconnected.setVisibility(View.INVISIBLE);
        }
        if (father.isNew()) {
            father_new.setVisibility(View.VISIBLE);
        } else {
            father_new.setVisibility(View.INVISIBLE);
        }

        father_name.setText(father.getName());
        final FamilyItem finalFather = father;
        final boolean finalIsConnected = isConnected;
        father_icon.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (finalIsConnected) {
                    showConfigCancelDialog(finalFather);
                }
                return true;
            }
        });

    }

    /**
     * 超级管理员取消他人对宝宝的关注
     */
    private void SuperManagerCancelConnect(FamilyItem item) {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("baby_id", CommonUtils.getBabyId());
        params.put("rp_id", item.getId());

        HttpRequestUtil.doHttpPostRequest(mContext, PuTaoConstants.API_POST_BABY_CANCEL,
                new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), true,
                new HttpRequestUtil.RequestResponseListener() {
                    @Override
                    public void success(int statuscode, String response) {
                        try {
                            JSONObject json = new JSONObject(response);
                            String status = json.getString("status");
                            if (status.equals(HttpRequestUtil.ResponseCode.api_code_200)) {

                            }
                            String msg = json.getString("msg");
                            showToast(msg);
                            doGetData();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void failed(int statuscode, String response) {
                        Loger.d("response:::" + response);
                    }
                });


    }

    /**
     * 获取宝宝的关系列表
     */
    void doGetData() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("baby_id", CommonUtils.getBabyId());
        HttpRequestUtil.doHttpGetRequest(mContext, PuTaoConstants.API_GET_BABY_RELATIONS,
                new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), true,
                new HttpRequestUtil.RequestResponseListener() {
                    @Override
                    public void success(int statuscode, String response) {
                        if (!StringHelper.isEmpty(response)) {

                            if (HttpRequestUtil.getResponseCode(response).equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                                doAnalyzeDataList(HttpRequestUtil.getResponseData(response));
                            } else {
                                showToast(HttpRequestUtil.getResponseErrorMsg(response));
                            }
                        }
                    }

                    @Override
                    public void failed(int statuscode, String response) {
                        Loger.d("response:::" + response);
                    }
                });
    }


    /**
     * 解析返回的数据
     *
     * @param data
     */
    void doAnalyzeDataList(JSONObject data) {
        mDatalist.clear();
        JSONArray list = data.optJSONArray("list");
        if (list != null) {
            for (int i = 0; i < list.length(); i++) {
                JSONObject o = null;
                try {
                    o = list.getJSONObject(i);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (o != null) {
                    String id = o.optString("id");
                    String name = o.optString("name");
                    String tag = o.optString("tag");
                    int is_admin = o.optInt("is_admin");
                    int is_new = o.optInt("is_new");
                    String avatar = o.optString("avatar");


                    FamilyItem item = new FamilyItem();
                    item.setId(id);
                    item.setTag(tag);
                    if (is_admin > 0) {
                        name = name + "(管理员)";
                        item.setAdmin(true);
                    } else {
                        item.setAdmin(false);
                    }
                    item.setName(name);
                    if (is_new > 0) {
                        item.setNew(true);
                    } else {
                        item.setNew(false);
                    }
                    item.setAvatar(avatar);
                    mDatalist.add(item);
                }
            }
        }

        admin_uid = data.optString("admin_uid");

        initView();
    }

    private void initView() {
        FamilyItem father = null;
        for (int i = 0; i < mDatalist.size(); i++) {
            FamilyItem item = mDatalist.get(i);
            if (RelationItem.Tag.FATHER.equals(item.getTag())) {
                father = item;
                mDatalist.remove(i);
                break;
            }
        }
        updateFatherView(father);


        FamilyItem mother = null;
        for (int i = 0; i < mDatalist.size(); i++) {
            FamilyItem item = mDatalist.get(i);
            if (RelationItem.Tag.MATHER.equals(item.getTag())) {
                mother = item;
                mDatalist.remove(i);
                break;
            }
        }
        updateMotherView(mother);

        mAdapter = new ActivityFamilyAdapter(mContext, mDatalist);
        mGridView.setAdapter(mAdapter);
        if(mDatalist.size()<1){
            mGridView.setVisibility(View.INVISIBLE);
        }
    }

}
